<template>
  <!-- 在线简历的展示 -->
  <div v-show="isModResume">
    <div class="on-line-shell-header">
      <!-- 个人信息部分 -->
      <div class="resume-userInfo">
        <div class="resume-userImg">
          <el-upload
            class="avatar-uploader"
            action="http://81.71.154.186:8088/api/avatars/uploadAvatar"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
          >
            <img
              v-if="ruleForm.avatar"
              :src="ruleForm.avatar"
              class="avatar"
              style="width: 100%; height: 100%; border-radius: 50%"
            />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
            <svg-icon icon-name="camera" class="resume-userImg-svg"></svg-icon>
          </el-upload>
        </div>
        <div class="resume-userInfo-text">
          <div class="resume-userName">{{ ruleForm.username }}</div>
          <div class="resume-userInfo-description">
            <div class="alignment" style="display: flex; align-items: center">
              <svg-icon icon-name="education" class="mr-5"></svg-icon
              >{{ ruleForm.education }}
            </div>
            <div class="alignment" style="display: flex; align-items: center">
              <svg-icon icon-name="telephone" class="mr-5"></svg-icon
              >{{ ruleForm.phone }}
            </div>
          </div>
          <div class="resume-userInfo-description">
            <div class="alignment" style="display: flex; align-items: center">
              <svg-icon icon-name="employmentStatus" class="mr-5"></svg-icon
              >{{
                ruleForm.studyStatus === 0
                  ? "在校生"
                  : ruleForm.studyStatus === 1
                  ? "应届毕业生"
                  : "已毕业"
              }}
            </div>
            <div class="alignment" style="display: flex; align-items: center">
              <svg-icon icon-name="email" class="mr-5"></svg-icon
              >{{ ruleForm.email }}
            </div>
          </div>
        </div>
      </div>
      <!-- 个人信息部分结束 -->
      <!-- 个人优势部分 -->
      <div class="personalAdvantages">
        <div
          style="
            display: flex;
            align-items: center;
            justify-content: space-between;
          "
        >
          <div style="display: flex; align-items: center">
            <div
              style="
                width: 4px;
                height: 30px;
                margin-right: 10px;
                background-color: #fff;
                border-radius: 10px;
                display: inline-block;
              "
            ></div>
            <div class="personalAdvantages-title">个人优势</div>
          </div>
          <div>
            <el-button
              style="
                padding: 10px;
                background-color: var(--button-color);
                color: var(--title-color);
              "
              type="success"
              plain
              @click="generatePdfFile"
              v-show="isModResume"
              :loading="isDownload"
              >导出pdf文件</el-button
            >
            <el-button
              style="
                padding: 10px;
                background-color: var(--buttontwo-color);
                color: #fff;
              "
              type="primary"
              plain
              @click="modResume"
              v-show="isModResume"
              >编辑资料</el-button
            >
          </div>
        </div>
        <div style="margin-left: 10px; margin-top: 10px">
          {{ ruleForm.introduction }}
        </div>
      </div>
    </div>
    <div class="on-line-shell-center">
      <!-- 期望岗位 -->
      <div class="expectedPosition">
        <div style="display: flex; align-items: center">
          <div
            style="
              width: 4px;
              height: 30px;
              margin-right: 10px;
              background-color: #fff;
              border-radius: 10px;
            "
          ></div>
          <div class="personalAdvantages-title">期望岗位</div>
        </div>
        <div class="expectedPosition-content">
          <span class="pr-10 border-r">{{ ruleForm.desiredPosition }}</span>
          <span class="pr-10 pl-10 border-r ml-5"
            >{{ ruleForm.minSalary }}&nbsp;-&nbsp;{{ ruleForm.maxSalary }}</span
          >
          <span class="pl-10 ml-5">{{ ruleForm.jobRegion }}</span>
        </div>
      </div>
      <!-- 教育经历 -->
      <div class="educationalExperience">
        <div style="display: flex; align-items: center">
          <div
            style="
              width: 4px;
              height: 30px;
              margin-right: 10px;
              background-color: #fff;
              border-radius: 10px;
            "
          ></div>
          <div class="personalAdvantages-title">教育经历</div>
        </div>
        <div class="educationalExperience-content">
          <span class="pr-10 border-r">{{
            ruleForm.eduExpsList[0].schoolName
          }}</span>
          <span class="pr-10 pl-10 border-r ml-5"
            >{{ ruleForm.eduExpsList[0].startTime }} &nbsp;-&nbsp;
            {{ ruleForm.eduExpsList[0].endTime }}</span
          >
          <span class="pr-10 pl-10 border-r ml-5">{{
            ruleForm.eduExpsList[0].major
          }}</span>
          <span class="pl-10 ml-5">{{
            ruleForm.eduExpsList[0].education
          }}</span>
        </div>
        <div class="majorCourses">
          <span>主修课程：</span>
          <span>{{ ruleForm.eduExpsList[0].mainCourse }}</span>
        </div>
      </div>
    </div>
    <div class="on-line-shell-center">
      <!-- 社团/组织经历 -->
      <div class="expectedPosition">
        <div style="display: flex; align-items: center">
          <div
            style="
              width: 4px;
              height: 30px;
              margin-right: 10px;
              background-color: #fff;
              border-radius: 10px;
            "
          ></div>
          <div class="personalAdvantages-title">社团/组织经历</div>
        </div>
        <div class="expectedPosition-content">
          <div class="info-text">
            {{ ruleForm.eduExpsList[0].schoolExperience }}
          </div>
        </div>
      </div>
      <!-- 专业技能 -->
      <div class="educationalExperience">
        <div style="display: flex; align-items: center">
          <div
            style="
              width: 4px;
              height: 30px;
              margin-right: 10px;
              background-color: #fff;
              border-radius: 10px;
            "
          ></div>
          <div class="personalAdvantages-title">专业技能及荣誉证书</div>
        </div>
        <div class="educationalExperience-content">
          <ul>
            <li>
              专业技能
              <div class="info-text">{{ ruleForm.professionalSkills }}</div>
            </li>
            <li style="margin-top: 10px">
              荣誉证书
              <div class="info-text">{{ ruleForm.certificates }}</div>
            </li>
          </ul>
        </div>
      </div>
    </div>
    <div class="on-line-shell-center">
      <!-- 工作/实习经历 -->
      <div class="expectedPosition">
        <div style="display: flex; align-items: center">
          <div
            style="
              width: 4px;
              height: 30px;
              margin-right: 10px;
              background-color: #fff;
              border-radius: 10px;
            "
          ></div>
          <div class="personalAdvantages-title">工作/实习经历</div>
        </div>
        <div style="margin-top: 10px; overflow: hidden">
          <div class="project-header">
            <div class="project-title">
              {{ ruleForm.workExpsList[0].companyName }}
            </div>
            <div class="project-role ml-5">
              {{ ruleForm.workExpsList[0].department }}
            </div>
          </div>
          <div class="project-header">
            <div class="project-role">
              {{ ruleForm.workExpsList[0].positionName }}
            </div>
            <div class="project-role ml-5">
              {{ ruleForm.workExpsList[0].startTime }}
              &nbsp;-&nbsp;
              {{ ruleForm.workExpsList[0].endTime }}
            </div>
          </div>
          <ul>
            <li>
              <span>内容：</span>
              <span class="info-text">{{
                ruleForm.workExpsList[0].workContent
              }}</span>
            </li>
          </ul>
        </div>
      </div>
      <!-- 项目经历 -->
      <div class="educationalExperience">
        <div style="display: flex; align-items: center">
          <div
            style="
              width: 4px;
              height: 30px;
              margin-right: 10px;
              background-color: #fff;
              border-radius: 10px;
            "
          ></div>
          <div class="personalAdvantages-title">项目经历</div>
        </div>
        <div class="educationalExperience-content">
          <div class="project-header">
            <div class="project-title">
              {{ ruleForm.proExpsList[0].proName }}
            </div>
            <div class="project-role ml-5">
              {{ ruleForm.proExpsList[0].proRole }}
            </div>
          </div>
          <div class="project-header">
            <div class="project-role">
              {{ ruleForm.proExpsList[0].proStartTime }}
              &nbsp;-&nbsp;
              {{ ruleForm.proExpsList[0].proEndTime }}
            </div>
          </div>
          <ul>
            <li>
              <span>内容：</span>
              <span class="info-text">{{
                ruleForm.proExpsList[0].proDesc
              }}</span>
            </li>
          </ul>
        </div>
      </div>
    </div>
  </div>
  <!-- 在线简历修改 -->
  <div v-show="!isModResume" style="color: #fff">
    <div style="display: flex">
      <!-- 编辑个人信息 -->
      <div>
        <div class="modUserInfo">编辑个人信息</div>
        <div class="modUserInfo-content">
          <div>
            姓名
            <el-input
              v-model="ruleForm.username"
              style="width: 240px"
              placeholder="请输入您的姓名"
              size="large"
              clearable
            />
          </div>
          <div>
            在读状态
            <el-select
              v-model="ruleForm.studyStatus"
              clearable
              placeholder="请选择您的在读状态"
              style="width: 240px"
              size="large"
            >
              <el-option label="在校生" :value="0" />
              <el-option label="应届毕业生" :value="1" />
              <el-option label="毕业生" :value="2" />
            </el-select>
          </div>
        </div>
        <div class="modUserInfo-content">
          <div>
            性别
            <el-radio-group v-model="ruleForm.sex" size="large">
              <el-radio-button label="男" :value="0" />
              <el-radio-button
                label="女"
                :value="1"
                style="margin-left: 10px"
              />
            </el-radio-group>
          </div>
          <div>
            学历
            <el-select
              v-model="ruleForm.education"
              clearable
              placeholder="请选择您的学历"
              style="width: 240px"
              size="large"
            >
              <el-option label="研究生" value="研究生" />
              <el-option label="本科" value="本科" />
              <el-option label="专科" value="专科" />
            </el-select>
          </div>
        </div>
        <div class="modUserInfo-content">
          <div>
            电话
            <el-input
              v-model="ruleForm.phone"
              style="width: 240px"
              placeholder="请输入您的电话"
              size="large"
              clearable
            />
          </div>
          <div>
            邮箱
            <el-input
              v-model="ruleForm.email"
              style="width: 240px"
              placeholder="请输入您的邮箱"
              size="large"
              clearable
            />
          </div>
        </div>
      </div>

      <!-- 编辑个人优势 -->
      <div>
        <div style="display: flex; width: 36vw; justify-content: space-between">
          <div class="modUserInfo">编辑个人优势</div>
          <div>
            <el-button style="padding: 10px" @click="exitEditing"
              >退出</el-button
            >
            <el-button
              style="
                padding: 10px;
                background-color: var(--button-color);
                color: #000;
              "
              type="primary"
              @click="saveResume"
              >保存</el-button
            >
          </div>
        </div>
        <div class="modUserInfo-content">
          <div>
            个人优势
            <el-input
              v-model="ruleForm.introduction"
              style="width: 580px"
              :rows="9"
              type="textarea"
              placeholder="请输入您的个人简介"
            />
          </div>
        </div>
      </div>
    </div>
    <div style="display: flex">
      <!-- 编辑求职期望 -->
      <div>
        <div class="modUserInfo">编辑求职期望</div>
        <div class="modUserInfo-content">
          <div>
            期望地区
            <el-cascader
              v-model="jobRegion"
              placeholder="请选择期望地区"
              :options="options"
              :show-all-levels="false"
              :props="props"
              @change="handleChange"
              filterable
            />
          </div>
          <div>
            期望岗位
            <el-autocomplete
              v-model="ruleForm.desiredPosition"
              :fetch-suggestions="querySearchForJob"
              clearable
              class="inline-input w-50"
              placeholder="请输入您的岗位"
              size="large"
              style="margin: 5px"
            />
          </div>
          <div>
            期望薪资
            <div
              style="
                height: 50px;
                display: flex;
                align-items: center;
                padding: 0;
              "
            >
              <div>
                <el-select
                  v-model="ruleForm.minSalary"
                  clearable
                  placeholder="最低薪资"
                  style="width: 140px"
                  size="large"
                  @change="updateMaxSalaryOptions"
                >
                  <el-option
                    v-for="option in minSalaryOptions"
                    :key="option.value"
                    :label="option.label"
                    :value="option.value"
                  />
                </el-select>
              </div>
              <div>至</div>
              <div>
                <el-select
                  v-model="ruleForm.maxSalary"
                  clearable
                  placeholder="最高薪资"
                  style="width: 140px"
                  size="large"
                >
                  <el-option
                    v-for="option in maxSalaryOptions"
                    :key="option.value"
                    :label="option.label"
                    :value="option.value"
                  />
                </el-select>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div style="display: flex">
      <!-- 编辑教育经历 -->
      <div>
        <div class="modUserInfo">编辑教育经历</div>
        <div class="modUserInfo-content">
          <div>
            学校名称
            <el-autocomplete
              v-model="ruleForm.eduExpsList[0].schoolName"
              :fetch-suggestions="querySearch"
              clearable
              class="inline-input w-50"
              placeholder="请选择您的院校"
              size="large"
              style="margin: 5px"
            />
          </div>
          <div>
            专业
            <el-autocomplete
              v-model="ruleForm.eduExpsList[0].major"
              :fetch-suggestions="querySearchForMajor"
              clearable
              class="inline-input w-50"
              placeholder="请选择您的专业"
              size="large"
              style="margin: 5px"
            />
          </div>
          <div>
            学历
            <el-select
              v-model="ruleForm.eduExpsList[0].education"
              clearable
              placeholder="请选择您的学历"
              style="width: 240px"
              size="large"
            >
              <el-option label="研究生" value="研究生" />
              <el-option label="本科" value="本科" />
              <el-option label="专科" value="专科" />
            </el-select>
          </div>
          <div>
            主修课程
            <el-input
              v-model="ruleForm.eduExpsList[0].mainCourse"
              style="width: 240px"
              placeholder="Please input"
              clearable
              size="large"
            />
          </div>
        </div>
        <div class="modUserInfo-content">
          <div style="display: flex; width: 550px">
            在校时间
            <el-date-picker
              v-model="ruleForm.eduExpsList[0].startTime"
              type="date"
              placeholder="开始时间"
              class="ml-5"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
            />
            <span class="ml-5">-</span>
            <el-date-picker
              v-model="ruleForm.eduExpsList[0].endTime"
              type="date"
              placeholder="结束时间"
              class="ml-5"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
            />
          </div>
        </div>
        <div class="modUserInfo-content">
          <div style="display: flex; width: 480px; flex-direction: column">
            社团经历
            <div>
              <el-input
                v-model="ruleForm.eduExpsList[0].schoolExperience"
                style="width: 480px"
                :autosize="{ minRows: 4, maxRows: 6 }"
                type="textarea"
                placeholder="请输入您的社团经历"
              />
            </div>
          </div>
          <div style="display: flex; width: 240px; flex-direction: column">
            专业技能
            <div>
              <el-input
                v-model="ruleForm.professionalSkills"
                style="width: 240px"
                :autosize="{ minRows: 4, maxRows: 6 }"
                type="textarea"
                placeholder="请输入您的专业技能"
              />
            </div>
          </div>
          <div style="display: flex; width: 240px; flex-direction: column">
            证书荣誉
            <div>
              <el-input
                v-model="ruleForm.certificates"
                style="width: 240px"
                :autosize="{ minRows: 4, maxRows: 6 }"
                type="textarea"
                placeholder="请输入您的证书荣誉"
              />
            </div>
          </div>
        </div>
      </div>
    </div>
    <div style="display: flex">
      <!-- 添加工作/实习经历 -->
      <div>
        <div class="modUserInfo">编辑工作/实习经历</div>
        <div class="modUserInfo-content">
          <div>
            公司名称
            <el-input
              v-model="ruleForm.workExpsList[0].companyName"
              style="width: 240px"
              placeholder="请输入公司名称"
              size="large"
              clearable
            />
          </div>
          <div>
            职位名称
            <el-autocomplete
              v-model="ruleForm.desiredPositiioin"
              :fetch-suggestions="querySearchForJob"
              clearable
              class="inline-input w-50"
              placeholder="请输入职位名称"
              size="large"
              style="margin: 5px"
            />
          </div>
        </div>
        <div class="modUserInfo-content">
          <div>
            所属部门
            <el-input
              v-model="ruleForm.workExpsList[0].department"
              style="width: 240px"
              placeholder="请输入所属部门"
              size="large"
              clearable
            />
          </div>
          <div style="display: flex; flex-direction: column">
            在职时间
            <div style="display: flex">
              <el-date-picker
                v-model="ruleForm.workExpsList[0].startTime"
                type="date"
                placeholder="开始时间"
                class="ml-5"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
              />
              <span class="ml-5">-</span>
              <el-date-picker
                v-model="ruleForm.workExpsList[0].endTime"
                type="date"
                placeholder="结束时间"
                class="ml-5"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
              />
            </div>
          </div>
        </div>

        <div class="modUserInfo-content">
          <div>
            工作内容
            <el-input
              v-model="ruleForm.workExpsList[0].workContent"
              style="width: 480px"
              :autosize="{ minRows: 4, maxRows: 6 }"
              type="textarea"
              placeholder="请输入您在工作时候的内容"
            />
          </div>
        </div>
      </div>

      <!-- 编辑个人优势 -->
      <div>
        <div class="modUserInfo">编辑项目经历</div>
        <div class="modUserInfo-content">
          <div>
            项目名称
            <el-input
              v-model="ruleForm.proExpsList[0].proName"
              style="width: 240px"
              placeholder="请输入您的项目名称"
              size="large"
              clearable
            />
          </div>
          <div>
            项目角色
            <el-input
              v-model="ruleForm.proExpsList[0].proRole"
              style="width: 240px"
              placeholder="请输入您的项目角色"
              size="large"
              clearable
            />
          </div>
        </div>
        <div class="modUserInfo-content">
          <!-- <div>
            项目链接
            <el-input
              v-model="ruleForm.proExpsList[0].proRole"
              style="width: 240px"
              placeholder="请输入您的姓名"
              size="large"
              clearable
            />
          </div> -->
          <div style="display: flex; flex-direction: column">
            在职时间
            <div style="display: flex">
              <el-date-picker
                v-model="ruleForm.proExpsList[0].proStartTime"
                type="date"
                placeholder="开始时间"
                class="ml-5"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
              />
              <span class="ml-5">-</span>
              <el-date-picker
                v-model="ruleForm.proExpsList[0].proEndTime"
                type="date"
                placeholder="结束时间"
                class="ml-5"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
              />
            </div>
          </div>
        </div>
        <div class="modUserInfo-content">
          <div>
            项目描述
            <el-input
              v-model="ruleForm.proExpsList[0].proDesc"
              style="width: 480px"
              :autosize="{ minRows: 4, maxRows: 6 }"
              type="textarea"
              placeholder="请输入您在工作时候的内容"
            />
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import {
  ElMessage,
  type FormInstance,
  type FormRules,
  type UploadProps,
} from "element-plus";
import { onMounted, reactive, watch, ref } from "vue";
import { useRoute } from "vue-router";
import {
  getOnlineResume,
  updateOnlineResume,
  addOnlineResume,
  generate,
} from "@/api/onlineResume";
import { useUserInfor } from "@/stores/userInfo";

const userStore = useUserInfor();

//在线简历部分
interface RuleForm {
  id: number; //简历id
  username: string; //姓名
  sex: number;
  phone: string; //联系电话
  education: string; //学历水平
  email: string; //邮箱
  avatar: string; //头像
  studyStatus: number; //阶段：应届毕业生
  jobRegion: string; //期望地区
  desiredPosition: string; //期望工作
  minSalary: string; //期望最小薪资
  maxSalary: string; //期望最大薪资
  introduction: string; //个人优势
  professionalSkills: string; //专业技能
  certificates: string; //证书
  eduExpsList: [
    {
      //教育经历
      schoolName: string; //毕业院校
      major: string; //专业
      education: string; //学历
      discipline: string; //学科
      mainCourse: string; //主修课程
      schoolExperience: string; //校内经历
      startTime: string; //入学时间
      endTime: string; //毕业时间
    }
  ];
  workExpsList: [
    {
      //工作经历
      companyName: string; //工作名称：软件协会官网
      positionName: string; //职位名称
      department: string; //所属部门
      workContent: string; //工作内容
      startTime: string; //入职时间
      endTime: string; //离职时间
    }
  ];
  proExpsList: [
    {
      //项目经验
      proName: string; //项目名称
      proRole: string; //项目角色
      proDesc: string; //项目内容
      proStartTime: string; //项目开始时间
      proEndTime: string; //项目结束时间
    }
  ];
}

// const ruleFormRef = ref<FormInstance>();
let ruleForm = reactive<RuleForm>({
  id: 0,
  username: "",
  sex: 0,
  phone: "",
  education: "",
  email: "",
  avatar: "",
  studyStatus: 0,
  jobRegion: "",
  desiredPosition: "",
  minSalary: "",
  maxSalary: "",
  introduction: "",
  professionalSkills: "",
  certificates: "",
  eduExpsList: [
    {
      schoolName: "", //毕业院校
      major: "", //专业
      education: "", //学历
      discipline: "", //学科
      mainCourse: "", //主修课程
      schoolExperience: "", //校内经历
      startTime: "", //入学时间
      endTime: "", //毕业时间
    },
  ],
  workExpsList: [
    {
      companyName: "", //工作名称：软件协会官网
      positionName: "", //职位名称
      department: "", //所属部门
      workContent: "", //工作内容
      startTime: "", //入职时间
      endTime: "", //离职时间
    },
  ],
  proExpsList: [
    {
      //项目经验
      proName: "", //项目名称
      proRole: "", //项目角色
      proDesc: "", //项目内容
      proStartTime: "", //项目开始时间
      proEndTime: "", //项目结束时间
    },
  ],
});

//查询简历
const route = useRoute();
const queryResume = async () => {
  try {
    const response = await getOnlineResume();
    console.log("查询成功");

    // 创建默认结构
    const defaultForm: RuleForm = {
      id: 0,
      username: "",
      sex: 0,
      phone: "",
      education: "",
      email: "",
      avatar: "",
      studyStatus: 0,
      jobRegion: "",
      desiredPosition: "",
      minSalary: "",
      maxSalary: "",
      introduction: "",
      professionalSkills: "",
      certificates: "",
      eduExpsList: [
        {
          schoolName: "", //毕业院校
          major: "", //专业
          education: "", //学历
          discipline: "", //学科
          mainCourse: "", //主修课程
          schoolExperience: "", //校内经历
          startTime: "", //入学时间
          endTime: "", //毕业时间
        },
      ],
      workExpsList: [
        {
          companyName: "", //工作名称：软件协会官网
          positionName: "", //职位名称
          department: "", //所属部门
          workContent: "", //工作内容
          startTime: "", //入职时间
          endTime: "", //离职时间
        },
      ],
      proExpsList: [
        {
          //项目经验
          proName: "", //项目名称
          proRole: "", //项目角色
          proDesc: "", //项目内容
          proStartTime: "", //项目开始时间
          proEndTime: "", //项目结束时间
        },
      ],
    };

    // 递归合并函数
    const mergeObjects = (target: any, source: any) => {
      for (const key of Object.keys(target)) {
        if (source && source.hasOwnProperty(key)) {
          if (Array.isArray(target[key])) {
            // 处理数组合并
            const sourceArray = source[key] || [];
            const targetArray = target[key] || [];
            const mergedArray = [];
            const maxLength = Math.max(sourceArray.length, targetArray.length);
            for (let i = 0; i < maxLength; i++) {
              mergedArray[i] = {
                ...(targetArray[i] || {}), // 默认数组中的元素
                ...(sourceArray[i] || {}), // 源数组中的元素
              };
            }
            target[key] = mergedArray;
          } else if (typeof target[key] === "object" && target[key] !== null) {
            mergeObjects(target[key], source[key]);
          } else {
            target[key] = source[key] ?? target[key];
          }
        }
      }
    };

    // 执行合并
    mergeObjects(defaultForm, response.data);

    // 保持响应式
    Object.assign(ruleForm, defaultForm);
    console.log(ruleForm);
  } catch (error) {
    console.error("Error fetching resume:", error);
  }
};
//绑定
onMounted(queryResume);

// 地区
//获取地区信息
userStore.getProvinceList();

const jobRegion = ref([]);
//开启多选
const props = { multiple: true };

const options = userStore.provinceList.map((provinceItem) => ({
  value: provinceItem.province,
  label: provinceItem.province,
  children: provinceItem.city.map((cityItem) => ({
    value: cityItem,
    label: cityItem,
  })),
}));
const handleChange = (values) => {
  if (values.length > 3) {
    jobRegion.value = values.slice(0, 3);
    // 可以在这里添加一些用户提示，告知用户只能选择三个
    ElMessage.warning("最多只能选择三个地区");
  }
  console.log(jobRegion.value);

  ruleForm.jobRegion = "";
  for (let i = 0; i < jobRegion.value.length; i++) {
    ruleForm.jobRegion += jobRegion.value[i][1];
    if (i < jobRegion.value.length - 1) {
      ruleForm.jobRegion += ","; // 添加逗号分隔符
    }
  }
};

//自动补全职位名称
interface RestaurantItem {
  value: string;
}
userStore.getJobNamesList(); // 获取学校列表

// 假设 userStore 中有 schoolList，且 schoolList 是字符串数组
// 将字符串数组转换为符合 RestaurantItem 接口的数组
const JobRestaurants = ref<RestaurantItem[]>(
  userStore.jobList.map((job) => ({ value: job }))
);

const querySearchForJob = (
  queryString: string,
  cb: (results: RestaurantItem[]) => void
) => {
  if (!JobRestaurants.value) {
    // 如果 JobRestaurants.value 是 undefined，返回空数组
    cb([]);
    return;
  }
  const results = queryString
    ? JobRestaurants.value.filter(createJobFilter(queryString))
    : JobRestaurants.value;

  // 调用回调函数返回建议列表
  cb(results);
};

const createJobFilter = (queryString: string) => {
  return (restaurant: RestaurantItem) => {
    return (
      restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0
    );
  };
};

//薪资的控制逻辑
// 定义最小薪资的选项
const minSalaryOptions = ref([
  { label: "1k", value: "1k" },
  { label: "2k", value: "2k" },
  { label: "3k", value: "3k" },
  { label: "4k", value: "4k" },
  { label: "5k", value: "5k" },
  { label: "6k", value: "6k" },
  { label: "7k", value: "7k" },
  { label: "8k", value: "8k" },
  { label: "9k", value: "9k" },
  { label: "10k", value: "10k" },
  { label: "15k", value: "15k" },
  { label: "20k", value: "20k" },
]);
// 定义最大薪资的选项
const maxSalaryOptions = ref<RestaurantItem[]>([]);

// 监听最小薪资的变化
// 监听最小薪资的变化
watch(
  () => ruleForm.minSalary,
  (newMinSalary) => {
    if (newMinSalary) {
      // 将字符串转换为数字进行计算
      const minSalaryValue = parseInt(newMinSalary.replace("k", ""), 10);
      const maxSalaryValue = minSalaryValue + 5; // 最大薪资比最小薪资大 5k

      // 动态生成最大薪资的选项
      maxSalaryOptions.value = minSalaryOptions.value.filter((option) => {
        const optionValue = parseInt(option.value.replace("k", ""), 10);
        return optionValue > minSalaryValue && optionValue <= maxSalaryValue;
      });

      // 默认选择第一个符合条件的选项
      ruleForm.maxSalary = maxSalaryOptions.value[0]?.value || "";
    } else {
      // 如果最小薪资为空，清空最大薪资选项
      maxSalaryOptions.value = [];
      ruleForm.maxSalary = "";
    }
  }
);
// 手动更新最大薪资选项（用于初始化或其他逻辑）
const updateMaxSalaryOptions = () => {
  watch(
    () => ruleForm.minSalary,
    (newMinSalary) => {
      if (newMinSalary) {
        const newMaxOptions = minSalaryOptions.value.filter(
          (option) => option.value > newMinSalary
        ) as { label: string; value: string }[];

        maxSalaryOptions.value = newMaxOptions;

        const defaultMaxSalary = newMaxOptions[0]?.value || null;
        // ruleForm.maxSalary = defaultMaxSalary;
        ruleForm.maxSalary = defaultMaxSalary as string;
      } else {
        maxSalaryOptions.value = [];
        ruleForm.maxSalary = "";
      }
    }
  );
};

//自动补全学校名称
interface RestaurantItem {
  value: string;
}
userStore.getSchoolList(""); // 获取学校列表

// 假设 userStore 中有 schoolList，且 schoolList 是字符串数组
// 将字符串数组转换为符合 RestaurantItem 接口的数组
const restaurants = ref<RestaurantItem[]>(
  userStore.schoolList.map((school) => ({ value: school }))
);

const querySearch = (
  queryString: string,
  cb: (results: RestaurantItem[]) => void
) => {
  if (!restaurants.value) {
    // 如果 restaurants.value 是 undefined，返回空数组
    cb([]);
    return;
  }
  const results = queryString
    ? restaurants.value.filter(createFilter(queryString))
    : restaurants.value;

  // 调用回调函数返回建议列表
  cb(results);
};

const createFilter = (queryString: string) => {
  return (restaurant: RestaurantItem) => {
    return (
      restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0
    );
  };
};
//自动补全专业名称
interface RestaurantItem {
  value: string;
}
userStore.getMajorList(""); // 获取学校列表

// 假设 userStore 中有 schoolList，且 schoolList 是字符串数组
// 将字符串数组转换为符合 RestaurantItem 接口的数组
const majorRestaurants = ref<RestaurantItem[]>(
  userStore.majorList.map((major) => ({ value: major }))
);
const querySearchForMajor = (
  queryString: string,
  cb: (results: RestaurantItem[]) => void
) => {
  if (!majorRestaurants.value) {
    // 如果 restaurants.value 是 undefined，返回空数组
    cb([]);
    return;
  }
  const results = queryString
    ? majorRestaurants.value.filter(createMajorFilter(queryString))
    : majorRestaurants.value;

  // 调用回调函数返回建议列表
  cb(results);
};

const createMajorFilter = (queryString: string) => {
  return (restaurant: RestaurantItem) => {
    return (
      restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0
    );
  };
};

//控制在线简历的编辑与展示
const isModResume = ref(true);
//改变在线简历的编辑与展示
const modResume = () => {
  isModResume.value = false;
};

//退出编辑
const exitEditing = () => {
  queryResume();
  isModResume.value = true;
};

//更新在线简历
const updateResumeData = async () => {
  try {
    const response = await updateOnlineResume(ruleForm);
    if (response.code === 200) {
      console.log("更新成功:", response.data);
      // queryResume();
      isModResume.value = true;
      queryResume();
    } else {
      console.log("更新失败", response.message);
      queryResume();
    }
  } catch (error) {
    console.error("更新失败:", error);
    queryResume();
  }
};

const addResumeData = async () => {
  try {
    const response = await addOnlineResume(ruleForm);
    if (response.code === 200) {
      console.log("增加简历成功");
      queryResume();
      isModResume.value = true;
    } else {
      console.log("增加失败", response.message);
      queryResume();
    }
  } catch (error) {
    console.error("增加简历失败:", error);
    queryResume();
  }
};

//保存在线简历
const saveResume = () => {
  if (ruleForm.id !== 0) {
    updateResumeData();
  } else {
    addResumeData();
  }
};

//导出简历为pdf文件
const isDownload = ref(false);
const generatePdfFile = async () => {
  isDownload.value = true;
  try {
    const response = await generate(ruleForm);
    if (response.code === 200) {
      console.log("简历生成成功");
      window.open(response.data);
      // queryResume();
      isDownload.value = false;
    } else {
      console.log("简历生成失败", response.message);
      isDownload.value = false;
    }
  } catch (error) {
    console.error("简历生成失败:", error);
    isDownload.value = false;
  }
};

// 头像部分
const handleAvatarSuccess: UploadProps["onSuccess"] = (
  response,
  uploadFile
) => {
  ruleForm.avatar = response.data;
  saveResume();
};

// const submitForm = async (formEl: FormInstance | undefined) => {
//   if (!formEl) return;
//   await formEl.validate((valid, fields) => {
//     if (valid) {
//       console.log("submit!");
//     } else {
//       console.log("error submit!", fields);
//     }
//   });
// };
</script>

<style lang="scss" scoped>
// 在线简历部分
.on-line-shell-header {
  width: 100%;
  display: flex;
  flex-direction: row;
  align-items: flex-start;

  .resume-userInfo {
    display: flex;
    align-items: center;
    width: 38%;

    .avatar-uploader {
      width: 100%;
      height: 100%;
    }

    .resume-userImg {
      width: 100px;
      height: 100px;
      background-color: #fff;
      border-radius: 50%;
    }

    .resume-userImg:hover {
      background-color: rgb(114, 115, 117);
    }

    .resume-userImg-svg {
      display: none;
    }

    .resume-userImg:hover .resume-userImg-svg {
      display: block;
    }

    .resume-userImg:hover .avatar {
      display: none;
    }

    .resume-userImg:hover .avatar-uploader-icon {
      display: none;
    }

    //个人信息
    .resume-userInfo-text {
      color: #fff;
      margin-left: 20px;
      margin-top: 10px;

      .resume-userName {
        font-size: 30px;
      }

      .resume-userInfo-description {
        margin-top: 5px;
        font-size: 14px;
        display: flex;

        div {
          margin-left: 10px;
        }
      }
    }
  }

  //个人优势
  .personalAdvantages {
    width: 640px;
    // height: 100px;
    margin-left: 50px;
    color: #fff;
  }
}

.on-line-shell-center {
  width: 100%;
  color: #fff;
  margin-top: 20px;
  display: flex;

  .expectedPosition {
    width: 542px;

    .expectedPosition-content {
      margin-top: 10px;
    }
  }

  .educationalExperience {
    width: 542px;
    margin-left: 50px;

    .educationalExperience-content {
      margin-top: 10px;
      overflow: hidden;
    }
  }
}

.project-header {
  display: flex;
  width: 515px;
  justify-content: flex-start;
  font-size: 18px;
}

//在线简历编辑部分
.modUserInfo {
  font-size: 20px;
  width: 50%;
}

.modUserInfo-content {
  display: flex;
  width: 100%;

  div {
    width: 243px;
    padding: 5px;
  }
}

:deep(.el-radio-button:first-child .el-radio-button__inner) {
  padding: 12px 39px;
  border-radius: 5px;
}

:deep(.el-radio-button:last-child .el-radio-button__inner) {
  padding: 12px 39px;
  border-radius: 5px;
}

.on-line-shell-footer {
  width: 100%;
  color: #fff;
  margin-top: 20px;
  display: flex;

  .workExperience {
    width: 395px;

    .workExperience-content {
    }
  }
}

.personalAdvantages-title {
  display: inline-block;
  font-size: 20px;
}

li {
  list-style: none;
}

.ml-5 {
  margin-left: 10px;
}
</style>
